﻿using System.Collections.Generic;
using Clipping.Infrastructure.Interfaces;
using Clipping.Infrastructure.Models;

namespace Clipping.SearchEnginePageParsers
{
   public class BaiduWebPageParser : ISearchEnginePageParse
    {
        public void Parse(string html, out List<News> news, out string nextPageUrl)
        {
            news = new List<News>();
            nextPageUrl = null;
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(html);

            var liNav = doc.CreateNavigator();
            var lis = liNav.Select("//table[@class='result']");
            while (lis.MoveNext())
            {
                News n = new News();

                var li = lis.Current;

                var link = li.SelectSingleNode("descendant::h3/a");
                if (link != null)
                {
                    n.Title = link.Value;
                    n.Url = link.GetAttribute("href", "");
                }

                var summary = li.SelectSingleNode("descendant::td/*[last()]");
                if (summary != null)
                {
                    string s = summary.InnerXml;
                    int brIndex = s.IndexOf("<br");
                    if (brIndex > 0)
                    {
                        s = s.Substring(0, brIndex);
                    }
                    HtmlAgilityPack.HtmlNode summaryNode = HtmlAgilityPack.HtmlNode.CreateNode(string.Format("<div>{0}</div>", s));
                    n.Summary = summaryNode.InnerText;
                }

                var time = summary.SelectSingleNode("span[@class='g']");
                if (time != null)
                {
                    string t = time.Value;
                    if (!string.IsNullOrEmpty(t))
                    { 
                        t=t.Trim();
                        int spaceIndex = t.LastIndexOf(" ");
                        if (spaceIndex > 0)
                        {
                            t = t.Substring(spaceIndex + 1);
                        }
                        n.PubDate = t;
                    }
                    
                }
                news.Add(n);
            }
            var nextPage = liNav.SelectSingleNode("//p[@id='page']/a[last()]");
            if (nextPage != null && nextPage.Value != null && nextPage.Value.Contains("下一页"))
            {
                nextPageUrl = nextPage.GetAttribute("href", "");
            }

        }
    }
}
